package com.jeecg.demo.controller;
import com.google.common.primitives.Bytes;
import com.jeecg.demo.entity.CommodityvarietyEntity;
import com.jeecg.demo.service.CommodityvarietyServiceI;
import com.jeecg.demo.util.GetUserTenantId;
import com.jeecg.demo.util.PopupDataBindUtil;
import com.jeecg.demo.page.CommodityvarietyPage;
import com.jeecg.demo.entity.CommodityvarietyattrEntity;
import java.util.ArrayList;
import java.util.List;
import java.text.SimpleDateFormat;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import org.apache.batik.css.engine.value.css2.UnicodeBidiManager;
import org.apache.commons.lang3.StringUtils;
import org.jeecgframework.core.common.controller.BaseController;
import org.jeecgframework.core.common.exception.BusinessException;
import org.jeecgframework.core.common.hibernate.qbc.CriteriaQuery;
import org.jeecgframework.core.common.model.json.AjaxJson;
import org.jeecgframework.core.common.model.json.DataGrid;
import org.jeecgframework.core.constant.Globals;
import org.jeecgframework.core.util.ExceptionUtil;
import org.jeecgframework.core.util.ResourceUtil;
import org.jeecgframework.core.util.StringUtil;
import org.jeecgframework.tag.core.easyui.TagUtil;
import org.jeecgframework.web.system.pojo.base.TSDepart;
import org.jeecgframework.web.system.service.SystemService;
import org.jeecgframework.core.util.MyBeanUtils;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.entity.vo.NormalExcelConstants;
import org.springframework.ui.ModelMap;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Map;

import jodd.typeconverter.Convert;


/**   
 * @Title: Controller
 * @Description: COMMODITYVARIETY
 * @author onlineGenerator
 * @date 2018-11-19 14:43:29
 * @version V1.0   
 *
 */
@Controller
@RequestMapping("/commodityvarietyController")
public class CommodityvarietyController extends BaseController {
	private static final Logger logger = LoggerFactory.getLogger(CommodityvarietyController.class);

	@Autowired
	private CommodityvarietyServiceI commodityvarietyService;
	@Autowired
	private SystemService systemService;
	@Autowired
	private PopupDataBindUtil bindUtil;

	/**
	 * COMMODITYVARIETY列表 页面跳转
	 * 
	 * @return
	 */
	@RequestMapping(params = "list")
	public ModelAndView list(HttpServletRequest request) {
		return new ModelAndView("com/jeecg/commodityvariety/commodityvarietyList");
	}

	/**
	 * easyui AJAX请求数据
	 * 
	 * @param request
	 * @param response
	 * @param dataGrid
	 * @param user
	 * @throws Exception 
	 */

	@RequestMapping(params = "datagrid")
	public void datagrid(CommodityvarietyEntity commodityvariety,HttpServletRequest request, HttpServletResponse response, DataGrid dataGrid) throws Exception {
		CriteriaQuery cq = new CriteriaQuery(CommodityvarietyEntity.class, dataGrid);
		// 查询条件组装器
		// 如果绑定非字典表数据，则更新排序格式，将新增的虚拟列改为原表中对应列
		dataGrid.setSort(dataGrid.getSort().replace("sectoridname", "sectorid"));
		dataGrid.setSort(dataGrid.getSort().replace("parentidname", "parentid"));
		org.jeecgframework.core.extend.hqlsearch.HqlGenerateUtil.installHql(cq, commodityvariety, request.getParameterMap());
		try{
		//自定义追加查询条件
		}catch (Exception e) {
			throw new BusinessException(e.getMessage());
		}
		GetUserTenantId getuserfun=new GetUserTenantId();
//		String idString = String.valueOf(systemService.findOneForJdbc(getuserfun.getSql(),getuserfun.getOrgcode()).get("worktypeid"));  
//		int worktypeid = Integer.parseInt(idString);
//		cq.eq("worktypeid", worktypeid);
		cq.add();
		this.commodityvarietyService.getDataGridReturn(cq, true);
		
		// 绑定非字典表数据
		bindUtil.BindDDName(dataGrid, "sector", "sectorname", "sectorid", "sectorid", "sectoridname");
		bindUtil.BindDDName(dataGrid, "commodityvariety", "varietyname", "varietyid", "parentid", "parentidname");
		
		TagUtil.datagrid(response, dataGrid);
	}

	/**
	 * 删除COMMODITYVARIETY
	 * 
	 * @return
	 */
	@RequestMapping(params = "doDel")
	@ResponseBody
	public AjaxJson doDel(CommodityvarietyEntity commodityvariety, HttpServletRequest request) {
		AjaxJson j = new AjaxJson();
		commodityvariety = systemService.getEntity(CommodityvarietyEntity.class, commodityvariety.getId());
		String message = "删除成功";
		try{
			commodityvarietyService.delMain(commodityvariety);
			systemService.addLog(message, Globals.Log_Type_DEL, Globals.Log_Leavel_INFO);
		}catch(Exception e){
			e.printStackTrace();
			message = "删除失败";
			throw new BusinessException(e.getMessage());
		}
		j.setMsg(message);
		return j;
	}

	/**
	 * 批量删除COMMODITYVARIETY
	 * 
	 * @return
	 */
	 @RequestMapping(params = "doBatchDel")
	@ResponseBody
	public AjaxJson doBatchDel(String ids,HttpServletRequest request){
		AjaxJson j = new AjaxJson();
		String message = "删除成功";
		try{
			for(String id:ids.split(",")){
				CommodityvarietyEntity commodityvariety = systemService.getEntity(CommodityvarietyEntity.class,
				Integer.parseInt(id)
				);
				commodityvarietyService.delMain(commodityvariety);
				systemService.addLog(message, Globals.Log_Type_DEL, Globals.Log_Leavel_INFO);
			}
		}catch(Exception e){
			e.printStackTrace();
			message = "删除失败";
			throw new BusinessException(e.getMessage());
		}
		j.setMsg(message);
		return j;
	}

	/**
	 * 添加COMMODITYVARIETY
	 * 
	 * @param ids
	 * @return
	 */
	@RequestMapping(params = "doAdd")
	@ResponseBody
	public AjaxJson doAdd(CommodityvarietyEntity commodityvariety,CommodityvarietyPage commodityvarietyPage, HttpServletRequest request) {
		List<CommodityvarietyattrEntity> commodityvarietyattrList =  commodityvarietyPage.getCommodityvarietyattrList();
		AjaxJson j = new AjaxJson();
		String message = "添加成功";
		try{
			String varietynameEn = commodityvariety.getVarietynameEn();
			if(varietynameEn !=null){
				byte[] bytes = varietynameEn.getBytes("UTF-8");
				String str = "[";
				for (byte b : bytes) {
					str+=b+",";
				}
				str = str.substring(0, str.length()-1);
				str+="]";
				commodityvariety.setVarietynameEn(str);
			}
		
			commodityvarietyService.addMain(commodityvariety, commodityvarietyattrList);
			systemService.addLog(message, Globals.Log_Type_INSERT, Globals.Log_Leavel_INFO);
		}catch(Exception e){
			e.printStackTrace();
			message = "添加失败";
			throw new BusinessException(e.getMessage());
		}
		j.setMsg(message);
		return j;
	}
	/**
	 * 更新COMMODITYVARIETY
	 * 
	 * @param ids
	 * @return
	 */
	@RequestMapping(params = "doUpdate")
	@ResponseBody
	public AjaxJson doUpdate(CommodityvarietyEntity commodityvariety,CommodityvarietyPage commodityvarietyPage, HttpServletRequest request) {
		List<CommodityvarietyattrEntity> commodityvarietyattrList =  commodityvarietyPage.getCommodityvarietyattrList();
		AjaxJson j = new AjaxJson();
		String message = "更新成功";
		try{
			String varietynameEn = commodityvariety.getVarietynameEn();
			if(varietynameEn !=null){
				byte[] bytes = varietynameEn.getBytes("UTF-8");
				String str = "[";
				for (byte b : bytes) {
					str+=b+",";
				}
				str = str.substring(0, str.length()-1);
				str+="]";
				commodityvariety.setVarietynameEn(str);
			}
			commodityvarietyService.updateMain(commodityvariety, commodityvarietyattrList);
			systemService.addLog(message, Globals.Log_Type_UPDATE, Globals.Log_Leavel_INFO);
		}catch(Exception e){
			e.printStackTrace();
			message = "更新失败";
			throw new BusinessException(e.getMessage());
		}
		j.setMsg(message);
		return j;
	}
	
	/**
	 * COMMODITYVARIETY新增页面跳转
	 * 
	 * @return
	 */
	@RequestMapping(params = "goAdd")
	public ModelAndView goAdd(CommodityvarietyEntity commodityvariety, HttpServletRequest req) {
		if (StringUtil.isNotEmpty(commodityvariety.getId())) {
			commodityvariety = commodityvarietyService.getEntity(CommodityvarietyEntity.class, commodityvariety.getId());
			req.setAttribute("commodityvarietyPage", commodityvariety);
		}
		return new ModelAndView("com/jeecg/commodityvariety/commodityvariety-add");
	}
	
	/**
	 * COMMODITYVARIETY编辑页面跳转
	 * 
	 * @return
	 * @throws UnsupportedEncodingException 
	 */
	@RequestMapping(params = "goUpdate")
	public ModelAndView goUpdate(CommodityvarietyEntity commodityvariety, HttpServletRequest req) throws UnsupportedEncodingException {
		if (StringUtil.isNotEmpty(commodityvariety.getId())) {
			commodityvariety = commodityvarietyService.getEntity(CommodityvarietyEntity.class, commodityvariety.getId());
			String varietynameEn = commodityvariety.getVarietynameEn();
			if (StringUtils.isNotEmpty(varietynameEn)) {
				varietynameEn = varietynameEn.substring(1, varietynameEn.length()-1);
				String[] split = varietynameEn.split(",");
				byte[] byteTostring = byteTostring(split);
				String string = new String(byteTostring,"UTF-8");
				commodityvariety.setVarietynameEn(string);
			}
			req.setAttribute("commodityvarietyPage", commodityvariety);
		}
		return new ModelAndView("com/jeecg/commodityvariety/commodityvariety-update");
	}
	
	//字符串数组转换为字节数组
	private byte[] byteTostring(String[] strdata){
		 int count = strdata.length;
		 byte[] bt = new byte[count];
		 int j = 0;
		 for (String str : strdata) {
			   bt[j] = (byte)Convert.toIntValue(str, 16);
			   j++;
			   while (j >= count){
				   break;
			   }
		 }
		return bt;
	}
	
	
	/**
	 * 加载明细列表[品种属性]
	 * 
	 * @return
	 */
	@RequestMapping(params = "commodityvarietyattrList")
	public ModelAndView commodityvarietyattrList(CommodityvarietyEntity commodityvariety, HttpServletRequest req) {
	
		//===================================================================================
		//获取参数
		Object id0 = commodityvariety.getId();
		//===================================================================================
		//查询-品种属性
	    String hql0 = "from CommodityvarietyattrEntity where 1 = 1 AND varietyid = ? ";
	    try{
	    	List<CommodityvarietyattrEntity> commodityvarietyattrEntityList = systemService.findHql(hql0,id0);
			req.setAttribute("commodityvarietyattrList", commodityvarietyattrEntityList);
		}catch(Exception e){
			logger.info(e.getMessage());
		}
		return new ModelAndView("com/jeecg/demo/commodityvarietyattrList");
	}

    /**
    * 导出excel
    *
    * @param request
    * @param response
    */
    @RequestMapping(params = "exportXls")
    public String exportXls(CommodityvarietyEntity commodityvariety,HttpServletRequest request, HttpServletResponse response, DataGrid dataGrid,ModelMap map) {
    	CriteriaQuery cq = new CriteriaQuery(CommodityvarietyEntity.class, dataGrid);
    	//查询条件组装器
    	org.jeecgframework.core.extend.hqlsearch.HqlGenerateUtil.installHql(cq, commodityvariety);
    	try{
    	//自定义追加查询条件
    	}catch (Exception e) {
    		throw new BusinessException(e.getMessage());
    	}
    	cq.add();
    	List<CommodityvarietyEntity> list=this.commodityvarietyService.getListByCriteriaQuery(cq, false);
    	List<CommodityvarietyPage> pageList=new ArrayList<CommodityvarietyPage>();
        if(list!=null&&list.size()>0){
        	for(CommodityvarietyEntity entity:list){
        		try{
        		CommodityvarietyPage page=new CommodityvarietyPage();
        		   MyBeanUtils.copyBeanNotNull2Bean(entity,page);
            	    Object id0 = entity.getId();
				    String hql0 = "from CommodityvarietyattrEntity where 1 = 1 AND varietyid = ? ";
        	        List<CommodityvarietyattrEntity> commodityvarietyattrEntityList = systemService.findHql(hql0,id0);
            		page.setCommodityvarietyattrList(commodityvarietyattrEntityList);
            		pageList.add(page);
            	}catch(Exception e){
            		logger.info(e.getMessage());
            	}
            }
        }
        map.put(NormalExcelConstants.FILE_NAME,"COMMODITYVARIETY");
        map.put(NormalExcelConstants.CLASS,CommodityvarietyPage.class);
        map.put(NormalExcelConstants.PARAMS,new ExportParams("COMMODITYVARIETY列表", "导出人:Jeecg",
            "导出信息"));
        map.put(NormalExcelConstants.DATA_LIST,pageList);
        return NormalExcelConstants.JEECG_EXCEL_VIEW;
	}

    /**
	 * 通过excel导入数据
	 * @param request
	 * @param
	 * @return
	 */
	@RequestMapping(params = "importExcel", method = RequestMethod.POST)
	@ResponseBody
	public AjaxJson importExcel(HttpServletRequest request, HttpServletResponse response) {
		AjaxJson j = new AjaxJson();
		MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
		Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
		for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
			MultipartFile file = entity.getValue();// 获取上传文件对象
			ImportParams params = new ImportParams();
			params.setTitleRows(2);
			params.setHeadRows(2);
			params.setNeedSave(true);
			try {
				List<CommodityvarietyPage> list =  ExcelImportUtil.importExcel(file.getInputStream(), CommodityvarietyPage.class, params);
				CommodityvarietyEntity entity1=null;
				for (CommodityvarietyPage page : list) {
					entity1=new CommodityvarietyEntity();
					MyBeanUtils.copyBeanNotNull2Bean(page,entity1);
		            commodityvarietyService.addMain(entity1, page.getCommodityvarietyattrList());
				}
				j.setMsg("文件导入成功！");
			} catch (Exception e) {
				j.setMsg("文件导入失败！");
				logger.error(ExceptionUtil.getExceptionMessage(e));
			}finally{
				try {
					file.getInputStream().close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			}
			return j;
	}
	/**
	* 导出excel 使模板
	*/
	@RequestMapping(params = "exportXlsByT")
	public String exportXlsByT(ModelMap map) {
		map.put(NormalExcelConstants.FILE_NAME,"COMMODITYVARIETY");
		map.put(NormalExcelConstants.CLASS,CommodityvarietyPage.class);
		map.put(NormalExcelConstants.PARAMS,new ExportParams("COMMODITYVARIETY列表", "导出人:"+ ResourceUtil.getSessionUser().getRealName(),
		"导出信息"));
		map.put(NormalExcelConstants.DATA_LIST,new ArrayList());
		return NormalExcelConstants.JEECG_EXCEL_VIEW;
	}
	/**
	* 导入功能跳转
	*
	* @return
	*/
	@RequestMapping(params = "upload")
	public ModelAndView upload(HttpServletRequest req) {
		req.setAttribute("controller_name", "commodityvarietyController");
		return new ModelAndView("common/upload/pub_excel_upload");
	}

 	
}
